package com.ztsoft.user.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(JWTUtils.class);
    //签名
    private static final String SECRET_KEY = "ZTsoft1234";
    //有效期时间30分钟
    private static final int EXPIRE_TIME = 300000000;

    private JWTUtils() {
    }

    /**
     * 生成token
     *
     * @param map payload
     * @return token
     */
    public static String sign(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();

        JWTCreator.Builder builder = JWT.create();
        //给withClaim赋值
        map.forEach(builder::withClaim);
        //默认30分钟过期
        instance.add(Calendar.MINUTE, EXPIRE_TIME);
        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 验证token
     *
     * @param token token
     */
    public static boolean verify(String token) {
        try {
            LOGGER.info("token：【{}】", token);
            JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
            return true;
        } catch (Exception e) {
            LOGGER.error("token验证出现异常", e);
            return false;
        }
    }

    /**
     * 获得token中指定字段的信息
     *
     * @param token token
     * @param claim 需要取值的字段
     * @return 值
     */
    public static String getTokenInfo(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            LOGGER.error("解析token出错", e);
            return null;
        }
    }
}